package com.reggielcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggielcy.common.CustomException;
import com.reggielcy.dto.SetmealDto;
import com.reggielcy.entity.Setmeal;
import com.reggielcy.entity.SetmealDish;
import com.reggielcy.mapper.SetmealMapper;
import com.reggielcy.service.SetmealDishService;
import com.reggielcy.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
  @auther teacher
  @date 2024/3/28
  @project reggie_take_out
  */


    @Service
    public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

        @Autowired
        private SetmealDishService setmealDishService;



    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐信息
        boolean save = this.save(setmealDto);

        Long setmealId = setmealDto.getId();

        //保存套餐及对应的菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);

    }
    @Transactional
    @Override
    public void deleteWithDish(List<Long> ids) {
        //判断套餐的启售状态
        //select count(*) from setmeal id in (ids...) where status=1
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);

        if (count>0){
             //如果已启售， status=1 则抛出异常 需要
            throw new CustomException("套餐正在售卖，无法删除");
        }

        //根据ids删除套餐表

        this.removeByIds(ids);
        //delete * from setmeal_dish where id in (ids...)
        //删除关系表，根据 setmeal_id 删除setmeal_dish表中的信息
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(setmealDishLambdaQueryWrapper);

    }
}
